<?php
/**
 * Created by PhpStorm.
 * User: 张旭
 * Date: 2020/8/12
 * Time: 8:58
 */

namespace app\index\controller;


use think\Controller;
use think\Db;
use think\facade\Cookie;
use think\facade\Request;

class Base extends Controller
{
    public $admin;
    // 程序初始化
    public function initialize()
    {
        $this->admin = json_decode(Cookie('admin'),true);
//        dump($this->admin);die;
        if (!$this->admin) return $this->redirect('/index/login/login');

        $role = findData('role','id='.$this->admin['rid']);
        // 登陆者为超级管理员时开放一切
        if ($role['id']==1){
            $where = ['pid'=>0,'status'=>1];
            $menu = selectData('menu',$where);
            foreach ($menu as $k => $v){
                $where1=['pid'=>$v['id']];
                $menu[$k]['item'] = selectData('menu',$where1);
            }
        }else{
            // 非管理员时查找对应身份的可用菜单并进行权限效验
            $mids = json_decode($role['rule'],true);
            $where = ['id'=>$mids,'pid'=>0,'status'=>1];
            
            $menu = selectData('menu',$where);
            
            foreach ($menu as $k => $v){
                $where1=['pid'=>$v['id'],'id'=>$mids,'status'=>1];
                $menu[$k]['item'] = selectData('menu',$where1);
            }
            if($this->admin['lv']==4){
                $menu = selectData('menu',$where);
                foreach ($menu as $k => $v){
                    $where1=['pid'=>$v['id'],'id'=>$mids,'status'=>1];
                   $menu = selectData('menu',$where1);
                }
            }
            // dump($menu);die;
            $where2=['id'=>$mids];
            $router = selectData('menu',$where2,'router');
            $this->checkPower($router);
        }

        $where3['aid'] = 1;
        $siteconfig = findData('siteconfig',$where3);
        $this->assign('siteconfig',$siteconfig);
        $admin = $this->admin;
        // if($admin['lv']==4&&$admin['type']==1){
        //     $if_finish = Db::name("renzheng")->where("admin_id",$admin['id'])->find();
        //     if(!$if_finish){
        //         $menu = [];
        //     }
        // }

        // if($admin['lv']==3){
        //     $if_finish = Db::name("school_renzheng")->where("admin_id",$admin['id'])->find();
        //     if(!$if_finish){
        //         $menu =[];
        //     }
        // }
        $this->assign('menu',$menu);

//        dump($menu);die;
    }

    // 权限效验
    protected function checkPower($router)
    {
        
        foreach ($router as $k => $v){
            if(!$v['router']) unset($v['router']);
            else $R[]=$v['router'];
        }
        $url = strtolower(rtrim(parse_url(Request::url())['path'],'/'));
        $R= array_to_lower($R);
        // dump($url);die;
        if (Request::controller() != 'Index'){
            if (!in_array($url,$R)) return $this->error('你没有权限访问…','/index/Index/welcome');
        }

    }



}